<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>事件对象</title>
    <style>
        *{
            margin:0;
            padding:0;
        }
        html,body,#app{
            width: 100%;
            height: 100%;
            overflow: hidden;
        }
        #app{
            background: url(./zhibo.png) no-repeat;
            background-size: cover;
        }
        #me{
            width: 150px;
            height: 200px;
            background: #568;
            position:absolute;
            left:0;
            top: 0;
        }

    </style>
</head>
<body>
    <div id="app">
        <div id="me"></div>
    </div>

    <script>
        
        //获取元素
        let me = document.querySelector('#me');
        let app = document.querySelector('#app');
        let one, two;
        //默认行为
        app.addEventListener('touchstart', function(e){
            e.preventDefault();
        })

        //绑定事件
        me.addEventListener('touchstart', function(e){
            //获取元素距离左侧的偏移量
            one = this.offsetLeft;
            //获取手指按下时, 距离窗口左侧的偏移量
            two = e.changedTouches[0].clientX;

            //
            this.t = this.offsetTop;
            this.y = e.changedTouches[0].clientY;
            //移除过渡
            this.style.transition = 'none';
        })

        me.addEventListener('touchmove', function(e){
            //获取手指滑动后, 距离窗口左侧的偏移量
            let three = e.changedTouches[0].clientX;
            //计算最终的 left 的值
            let left = three - (two - one);
            //判断
            if(left <= 0) left = 0;
            //右侧边界
            let maxLeft = app.offsetWidth - me.offsetWidth;
            if(left >= maxLeft) left = maxLeft;
            //设置
            me.style.left = left + 'px';

            //垂直方向的处理
            this._y = e.changedTouches[0].clientY;
            //计算
            let newTop = this._y - (this.y - this.t);
            me.style.top = newTop + 'px';
        })

        me.addEventListener('touchend', function(e){
            this.style.transition = 'left 0.5s';

            let newLeft;
            //计算中间状态的 left 的值
            let middleLeft = (app.offsetWidth - me.offsetWidth) / 2;
            // 判断
            if(me.offsetLeft <= middleLeft){
                newLeft = 0;
            }else{
                newLeft = app.offsetWidth - me.offsetWidth;
            }
            //设置
            me.style.left = newLeft + 'px';
        })

    </script>
</body>
</html>